package com.shenlong.controller;

import com.alibaba.fastjson.JSONObject;
import com.shenlong.annotation.UserLoginToken;
import com.shenlong.entity.User;
import com.shenlong.service.TokenService;
import com.shenlong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:Jiajie
 * @Date:2020/8/10 16:50
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    TokenService tokenService;

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public JSONObject login(User user) {
        JSONObject jsonObject = new JSONObject();
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            throw new RuntimeException("error:username和password都不能为空");
        }

        User loginUser = userService.getUserByUserName(user.getUsername());

        if (loginUser == null) {
            jsonObject.put("message", "登录失败，用户名不存在!");
            return jsonObject;
        }

        if (!loginUser.getPassword().equals(user.getPassword())) {
            jsonObject.put("message", "登录失败，密码错误!");
            return jsonObject;
        }
        String token = tokenService.getToken(loginUser);
        jsonObject.put("message", "登陆成功");
        jsonObject.put("token", token);

        return jsonObject;
    }

    @UserLoginToken
    @RequestMapping(path = "/getMessage", method = RequestMethod.GET)
    public String getMessage() {
        return "你已经通过验证";
    }
}
